import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import {
  Collapse,
  Table,
  Row,
  Col,
  Tag,
  Button,
  Modal,
  message,
  Pagination,
  Empty,
} from 'antd';
import { del_template, change_default } from '../../../../store/actions/order';
import { useNavigate } from 'react-router-dom';
import './index.scss';
const { Panel } = Collapse;
const { confirm } = Modal;


const CollapseCom = props => {
  const [messageApi, contextHolder] = message.useMessage();
  const { templates, onSearch, searchRes, del_template, change_default } =
    props;
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(2);
  const [pageData, setPageData] = useState([]);
  const navigate = useNavigate();
  // 表格
  const columnsPiece = [
    {
      title: '可配送区域',
      dataIndex: 'distributeArea',
      key: 'distributeArea',
      width: 250,
    },
    {
      title: '首件（个）',
      dataIndex: 'firstPiece',
      key: 'firstPiece',
    },
    {
      title: '运费（元）',
      dataIndex: 'unitFee',
      key: 'unitFee',
    },
    {
      title: '续件（个）',
      dataIndex: 'addPiece',
      key: 'addPiece',
    },
    {
      title: '续费（元）',
      dataIndex: 'addFee',
      key: 'addFee',
    },
  ];
  const columnsWeight = [
    {
      title: '可配送区域',
      dataIndex: 'distributeArea',
      key: 'distributeArea',
      width: 250,
    },
    {
      title: '首重（KG）',
      dataIndex: 'firstWeight',
      key: 'firstWeight',
    },
    {
      title: '运费（元）',
      dataIndex: 'unitFeeW',
      key: 'unitFeeW',
    },
    {
      title: '续重（KG）',
      dataIndex: 'addWeight',
      key: 'addWeight',
    },
    {
      title: '续费（元）',
      dataIndex: 'addFeeW',
      key: 'addFeeW',
    },
  ];
  // 删除模态框
  const showConfirm = id => {
    confirm({
      title: '确定要删除？',
      onOk() {
        del_template(id);
        messageApi.open({
          type: 'success',
          content: '删除成功',
          duration: 1,
        });
      },
      width: 250,
    });
  };
  // 折叠面板（默认全部展开）
  const defaultActiveKey = [];
  templates.forEach((el, i) => {
    defaultActiveKey.push(i);
  });
  // 修改默认状态
  const changeDefault = (id, e) => {
    e.stopPropagation();
    change_default(id);
    // 提示
    messageApi.open({
      type: 'success',
      content: '设置成功',
      duration: 1,
    });
    // 跳到第1页
    setPage(1);
  };
  // 分页
  const total = onSearch ? searchRes.length : templates.length;
  const pageChange = (page, pageSize) => {
    setPage(page);
    setPageSize(pageSize);
  };
  useEffect(() => {
    if (!onSearch) {
      setPageData(
        templates.filter(
          (_, i) =>
            (page - 1) * pageSize + 1 <= i + 1 && page * pageSize >= i + 1
        )
      );
    } else {
      setPageData(
        searchRes.filter(
          (_, i) =>
            (page - 1) * pageSize + 1 <= i + 1 && page * pageSize >= i + 1
        )
      );
    }
  }, [page, pageSize, templates, searchRes, onSearch]);
  // 复制模板
  const handleCopyClick = (el, e) => {
    e.stopPropagation();
    const { name, distributeArea, priceType } = el;
    const copyContent = `${name}：  可配送区域：${distributeArea}  计价方式：${priceType}`;
    navigator.clipboard.writeText(copyContent).then(
      function () {
        messageApi.open({
          type: 'success',
          content: '复制成功',
          duration: 1,
        });
      },
      function () {
        messageApi.open({
          type: 'success',
          content: '复制失败',
          duration: 1,
        });
      }
    );
  };
  return (
    <>
      {contextHolder}
      {pageData.length === 0 ? (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
      ) : (
        <>
          <Collapse bordered={true} defaultActiveKey={defaultActiveKey}>
            {pageData.map((el, i) => (
              <Panel
                header={
                  <Row align='middle'>
                    <Col span={5}>
                      {el.name}
                      {el.isDefault ? (
                        <Tag color='processing' style={{ marginLeft: 10 }}>
                          <span>默认模板</span>
                        </Tag>
                      ) : (
                        ''
                      )}
                    </Col>
                    <Col span={4}>
                      <span>关联商品：</span>
                      {el.relatedGoodsNum}
                    </Col>
                    <Col span={7}>
                      <span style={{ marginLeft: 20 }}>更新时间：</span>
                      {el.updateTime}
                    </Col>
                    <Col span={2}>
                      {el.isDefault ? (
                        ''
                      ) : (
                        <Button
                          type='link button'
                          onClick={e => {
                            changeDefault(el.id, e);
                          }}>
                          设为默认
                        </Button>
                      )}
                    </Col>
                    <Col sapn={6}>
                      <Button
                        type='link button'
                        onClick={e => {
                          handleCopyClick(el, e);
                        }}>
                        复制模板
                      </Button>
                      <Button
                        type='link button'
                        onClick={e => {
                          e.stopPropagation();
                          navigate('/home/template-detail', { state: el });
                        }}>
                        编辑
                      </Button>
                      <Button
                        type='link button'
                        onClick={e => {
                          e.stopPropagation();
                          showConfirm(el.id);
                        }}>
                        删除
                      </Button>
                    </Col>
                  </Row>
                }
                key={i}
                className='table-box'>
                <Table
                  columns={
                    el.priceType === '按件数' ? columnsPiece : columnsWeight
                  }
                  dataSource={[{ key: el.id, ...el }]}
                  pagination={false}
                />
              </Panel>
            ))}
          </Collapse>
          <Pagination
            total={total}
            current={page}
            pageSize={pageSize}
            showSizeChanger
            showQuickJumper
            showTotal={total => `共 ${total} 条`}
            style={{ marginTop: 20 }}
            defaultPageSize={2}
            pageSizeOptions={[2, 5, 10, 20]}
            onChange={pageChange}
          />
        </>
      )}
    </>
  );
};
export default connect(
  state => ({
    templates: state.templateReducer,
    onSearch: state.templateSearchReducer,
    searchRes: state.templateRes,
  }),
  { del_template, change_default }
)(CollapseCom);
